<template>
  <div class="page-certificate">
    <div class="certificate-container">
      <div class="breadcrumb">
        <Breadcrumb separator=">">
          <BreadcrumbItem to="/index">首页</BreadcrumbItem>
          <BreadcrumbItem>证书查询</BreadcrumbItem>
        </Breadcrumb>
      </div>
      <div class="certificate-content">
        <div class="certificate-left">
          <div class="search-box">
            <div class="search-box-tit">证书查询</div>
            <div class="search-form">
              <Form :model="form" :label-width="70">
                <FormItem label="查询类型">
                  <Select
                    v-model="form.type"
                    placeholder="请选择查询类型"
                    @on-change="typeChange"
                  >
                    <Option :value="1">编号查询</Option>
                    <Option :value="2">身份查询</Option>
                  </Select>
                </FormItem>
                <FormItem label="姓  名" v-if="form.type == 2">
                  <Input v-model="form.name" placeholder="请输入姓名"></Input>
                </FormItem>
                <FormItem label="身 份 证" v-if="form.type == 2">
                  <Input
                    v-model="form.idNumber"
                    placeholder="请输入身份证"
                  ></Input>
                </FormItem>
                <FormItem label="证书编号" v-if="form.type == 1">
                  <Input
                    v-model="form.certificateNo"
                    placeholder="请输入证书编号"
                  ></Input>
                </FormItem>
              </Form>
              <div class="search-submit-btn" @click="searchCertificate">
                查询
              </div>
            </div>
          </div>
          <div class="search-tips">
            <div class="tips-title">查询说明：</div>
            <div class="tips-content">
              查询方式可选择编号查询和身份查询<br/>编号查询：输入证书的编号<br/>身份查询：输入姓名和身份证号
            </div>
          </div>
        </div>
        <div class="certificate-right">
          <div
            class="certificate-box"
            v-for="(item, index) in certificateList"
            :key="index"
          >
            <div class="certificate-box-item" style="width:20%;">
              姓名：{{ item.name }}
            </div>
            <div class="certificate-box-item" style="width:30%;">
              证书编号：{{ item.certificateNo }}
            </div>
            <div class="certificate-box-item" style="width:30%;">
              证书类型：{{ item.certificateTypeName }}
            </div>
            <div class="certificate-box-item" style="width:20%;">
              <span
                class="certificate-btn"
                @click="previewFile(item.url, item.certificateNo)"
                >预览</span
              >
              <span
                class="certificate-btn"
                style="margin-left:20px;"
                @click="downloadExport(item.url, item.certificateNo)"
                >下载</span
              >
            </div>
          </div>
          <div class="certificate-empty-box" v-if="certificateList.length == 0">
            <Icon type="ios-alert-outline" size="70" />
            <p>没有查到证书哟 !</p>
          </div>
          <!-- <div class="certificate-list" v-if="certificateList.length > 0">
                    <div class="certificate-item"></div>
                </div>
                <div class="no-certificate" v-if="certificateList.length == 0">没有查询到证书</div> -->
        </div>
      </div>
    </div>
    <div class="preview-file-dialog" v-if="previewFileDialog">
      <pdf
        class="preview-pdf"
        v-if="previewFileType == 1"
        ref="pdf"
        :src="previewFileUrl"
        :page="currentPage"
        @num-pages="pageCount = $event"
        @page-loaded="currentPage = $event"
        @loaded="loadPdfHandler"
      >
      </pdf>
      <p class="preview-arrow" v-if="previewFileType == 1">
        <span
          @click="changePdfPage(0)"
          class="turn"
          :class="{ grey: currentPage == 1 }"
          >上一页</span
        >
        <span style="margin:0 20px;">{{ currentPage }} / {{ pageCount }}</span>
        <span
          @click="changePdfPage(1)"
          class="turn"
          :class="{ grey: currentPage == pageCount }"
          >下一页</span
        >
      </p>
      <img
        class="preview-img"
        v-if="previewFileType == 2"
        :src="previewFileUrl"
        alt=""
      />
      <Icon type="md-close close-preview" @click="previewFileDialog = false" />
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { downloadReport, searchCertificate } from "~/api/course";
export default {
  name: "certificate",
  data() {
    return {
      currentPage: 0, // pdf文件页码
      pageCount: 0, // pdf文件总页数
      pdfPages: 0, //pdf页数
      vuePdf: null, //vue-pdf对象
      previewFileDialog: false, //预览窗口弹窗
      previewFileType: 1, //1:pdf 2:文件
      // 预览文件地址
      previewFileUrl: null,
      form: {
        type: 1
      },
      certificateList: []
    };
  },
  created() {
    if (process.client) {
      this.vuePdf = require('vue-pdf')
    }
  },
  mounted() {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    async searchCertificate() {
      let params = {};
      if (this.form.type == 1) {
        if (!(this.form.certificateNo && this.form.certificateNo.trim())) {
          alert("请填写证书编号！");
          return;
        }
        if (!/^[0-9a-zA-Z_\-\.]{1,}$/.test(this.form.certificateNo)) {
          alert("请输入正确的证书编号！");
          return;
        }
        params = {
          certificateNo: this.form.certificateNo
        };
      } else {
        if (!(this.form.name && this.form.name.trim())) {
          alert("请填写姓名！");
          return;
        }
        if (!this.form.idNumber) {
          alert("请填写身份证！");
          return;
        }
        if (
          !/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            this.form.idNumber
          )
        ) {
          alert("请输入正确的身份证！");
          return;
        }
        params = {
          name: this.form.name,
          idNumber: this.form.idNumber
        };
      }
      this.SET_IS_LOADING(true);
      let result = await searchCertificate(params);
      if (result && result.data && result.data.code == 200) {
        this.certificateList = result.data.data;
        this.$Message.success("查询成功");
      } else {
        
      }
      this.SET_IS_LOADING(false);
    },
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--;
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.currentPage++;
        // console.log(this.currentPage)
      }
    },

    // pdf加载时
    loadPdfHandler(e) {
      this.currentPage = 1; // 加载的时候先加载第一页
    },
    // 证书预览
    async previewFile(url, certificateNo) {
      if (/\.pdf/.test(url)) {
        console.log("是pdf文件");
        this.previewFileType = 1;
        this.previewFileUrl = url;
        let CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/cmaps/"
        let loadingTask = this.vuePdf.default.createLoadingTask({
          url: url,
          cMapUrl: CMAP_URL,
          cMapPacked: true,
        });
        loadingTask.promise
          .then(pdf => {
            this.pdfPages = pdf.numPages;
            this.pageCount = pdf.numPages;
          })
          .catch(err => {
            console.error("pdf 加载失败", err);
          });
      } else {
        console.log("是图片");
        this.previewFileType = 2;
        this.previewFileUrl = url;
      }

      // this.previewFileUrl = url;
      this.previewFileDialog = true;
    },
    //证书下载
    async downloadExport(url, reportName) {
      this.SET_IS_LOADING(true);

      let result = await downloadReport(url);
      const content = result.data;
      const blob = new Blob([content]);
      let fileName = reportName + "." + url.replace(/(.*\.)/, ""); // 自定义文件名+后缀;
      if ("download" in document.createElement("a")) {
        console.log("非IE下载");
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        console.log("IE10+下载");
        navigator.msSaveBlob(content, fileName);
      }
      this.SET_IS_LOADING(false);
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
          time = parseInt(time);
        } else if (typeof time === "string") {
          time = time.replace(new RegExp(/-/gm), "/");
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
          return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return time_str;
    },
    typeChange(v) {
      if (v == 1) {
        this.form.name = "";
        this.form.idNumber = "";
      } else {
        this.form.certificateNo = "";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.page-certificate {
  min-height: 100vh;
  .preview-file-dialog {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 100vw;
    height: 100%;
    background: #fff;
    z-index: 10000000000000000;
    overflow: auto;
    .preview-btn {
      font-size: 16px;
      cursor: pointer;
      color: var(--theme-color);
    }
    .close-preview {
      position: fixed;
      right: 20px;
      top: 20px;
      font-size: 30px;
      cursor: pointer;
    }
    .preview-img {
      position: absolute;
      left: 0;
      // top: 0;
      right: 0;
      // bottom: 0;
      padding: 20px 0;
      max-width: 800px;
      margin: auto;
    }
    .preview-pdf {
      width: 800px;
      margin: 0 auto;
    }
    .preview-arrow {
      padding: 20px 0;
      text-align: center;
      font-size: 16px;
      .turn {
        cursor: pointer;
      }
    }
  }
  .certificate-container {
    width: 1200px;
    margin: 0 auto;
    padding-bottom: 30px;
    .breadcrumb {
      padding: 20px 0;
    }
    .certificate-content {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .certificate-left {
        width: 300px;
        .search-box {
          background: #fff;
          border: 1px solid #e8e8e8;
          .search-box-tit {
            background: var(--theme-color);
            text-align: center;
            line-height: 40px;
            font-size: 16px;
            color: #fff;
          }
          .search-form {
            padding: 10px 10px 10px 10px;
            .search-submit-btn {
              margin-top: 10px;
              margin-bottom: 20px;
              background: var(--theme-color);
              text-align: center;
              line-height: 30px;
              border-radius: 3px;
              font-size: 16px;
              color: #fff;
              cursor: pointer;
            }
          }
        }
        .search-tips {
          margin-top: 30px;
          .tips-title {
            font-size: 16px;
            margin-bottom: 10px;
          }
          .tips-content {
            border: 1px solid #e8e8e8;
            background: #fff;
            padding: 10px;
            line-height: 24px;
            font-size: 14px;
            min-height: 150px;
          }
        }
      }
      .certificate-right {
        width: 870px;
        box-sizing: border-box;
        padding: 0 10px;
        min-height: 40px;
        background: #fff;
        // .certificate-list{
        //     .certificate-item{}
        // }
        // .no-certificate{
        //     background: #fff;
        //     text-align: center;
        //     line-height: 40px;
        //     font-size: 16px;
        //     color: var(--theme-color);
        // }
        .certificate-box {
          width: 100%;
          // height: 170px;
          padding-bottom: 26px;
          padding-top: 26px;
          border-bottom: 1px solid #e6e6e6;
          font-size: 16px;
          display: flex;
          justify-content: space-between;
          text-align: center;
          .certificate-box-item {
            text-align: left;
            &:last-child {
              text-align: right;
            }
          }
          .certificate-btn {
            cursor: pointer;
            &:hover {
              color: var(--theme-color);
            }
          }
          &:last-child {
            border-bottom: none;
          }
        }
        .certificate-empty-box {
          padding: 50px 0;
          text-align: center;
          font-size: 16px;
          p {
            line-height: 50px;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.page-certificate {
  .ivu-form-item {
    margin-bottom: 6px;
  }
}
</style>
